/**
 * @file camera_thread.c
 * @brief 图像采集线程实现
 */

#include "action_camera.h"

/**
 * @brief 图像采集线程主函数
 * @param arg 线程参数
 * @return NULL
 */
void* camera_capture_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    shared_frame_t* frame;
    uint32_t frame_count = 0;
    uint64_t last_fps_time = 0;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] Camera thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] Camera thread started with valid ID: %d (pointer=%p)\n", *tid, (void*)tid);
    
    LOG_INFO("Camera capture thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    // 模拟摄像头初始化
    usleep(100000); // 100ms初始化时间
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 检查消息队列
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 0) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("Camera thread received shutdown message", 0);
                break;
            }
        }
        
        // 获取空闲帧缓冲区
        frame = frame_pool_acquire(&g_camera_system.frame_pool);
        if (!frame) {
            LOG_WARN("No free frame buffer available, dropping frame", 0);
            g_camera_system.stats.frames_dropped++;
            usleep(33000); // 30fps间隔
            continue;
        }
        
        // 模拟图像采集
        frame->frame_id = frame_count++;
        frame->timestamp = get_system_timestamp();
        frame->width = 1920;
        frame->height = 1080;
        frame->format = 1; // YUV420
        frame->size = frame->width * frame->height * 3 / 2;
        frame->is_keyframe = (frame_count % 30 == 1); // 每30帧一个关键帧
        
        // 模拟图像数据填充
        memset(frame->data, frame_count % 256, frame->size);
        
        atomic_store(&frame->ref_count, 1);
        
        // 发送给编码线程
        message_t video_msg = {
            .type = MSG_VIDEO_FRAME,
            .timestamp = frame->timestamp,
            .source_thread = *tid,
            .dest_thread = THREAD_ENCODER,
            .data_size = sizeof(void*)
        };
        memcpy(video_msg.data, &frame, sizeof(void*));
        
        if (message_queue_send(&g_camera_system.message_queues[THREAD_ENCODER], 
                              &video_msg) != 0) {
            LOG_WARN("Failed to send frame to encoder", 0);
            frame_pool_release(&g_camera_system.frame_pool, frame);
        }
        
        // 发送预览帧给UI线程
        atomic_fetch_add(&frame->ref_count, 1);
        message_t ui_msg = video_msg;
        ui_msg.dest_thread = THREAD_UI;
        
        if (message_queue_send(&g_camera_system.message_queues[THREAD_UI], 
                              &ui_msg) != 0) {
            LOG_DEBUG("Failed to send preview frame to UI", 0);
            atomic_fetch_sub(&frame->ref_count, 1);
        }
        
        // 统计更新
        g_camera_system.stats.frames_captured++;
        
        // FPS统计
        uint64_t current_time = get_system_timestamp();
        if (current_time - last_fps_time >= 1000000) { // 每秒统计一次
            LOG_DEBUG("Camera FPS: %u", frame_count - (uint32_t)(last_fps_time / 1000000 * 30), 0);
            last_fps_time = current_time;
        }
        
        // 帧率控制 (30fps)
        usleep(33000); // 33ms
    }
    
    LOG_INFO("Camera capture thread exiting", 0);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}

/**
 * @brief 视频编码线程主函数
 * @param arg 线程参数
 * @return NULL
 */
void* video_encoder_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    shared_frame_t* frame;
    uint32_t encoded_count = 0;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] Encoder thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] Encoder thread started with valid ID: %d (pointer=%p)\n", *tid, (void*)tid);
    
    LOG_INFO("Video encoder thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    // 模拟编码器初始化
    usleep(200000); // 200ms初始化时间
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 接收视频帧
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 100) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("Encoder thread received shutdown message", 0);
                break;
            }
            
            if (msg.type == MSG_VIDEO_FRAME) {
                memcpy(&frame, msg.data, sizeof(void*));
                
                // 模拟H.264编码处理
                usleep(10000); // 10ms编码时间
                
                // 创建编码后的数据消息
                message_t encoded_msg = {
                    .type = MSG_VIDEO_FRAME,
                    .timestamp = frame->timestamp,
                    .source_thread = *tid,
                    .dest_thread = THREAD_STORAGE,
                    .data_size = sizeof(void*)
                };
                memcpy(encoded_msg.data, &frame, sizeof(void*));
                
                // 发送给存储线程
                if (message_queue_send(&g_camera_system.message_queues[THREAD_STORAGE], 
                                      &encoded_msg) != 0) {
                    LOG_WARN("Failed to send encoded frame to storage", 0);
                    frame_pool_release(&g_camera_system.frame_pool, frame);
                } else {
                    encoded_count++;
                    g_camera_system.stats.frames_encoded++;
                }
                
                LOG_DEBUG("Encoded frame %u, timestamp: %lu", 
                         frame->frame_id, frame->timestamp);
            }
        }
    }
    
    LOG_INFO("Video encoder thread exiting, encoded %u frames", encoded_count);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}

/**
 * @brief 音频采集线程主函数
 * @param arg 线程参数
 * @return NULL
 */
void* audio_capture_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    uint32_t sample_count = 0;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] Audio thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] Audio thread started with valid ID: %d (pointer=%p)\n", *tid, (void*)tid);
    
    LOG_INFO("Audio capture thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    // 检查音频是否启用
    if (!g_camera_system.config.audio_enabled) {
        LOG_INFO("Audio disabled, thread going to sleep", 0);
        while (atomic_load(&g_camera_system.sync.system_running)) {
            if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 1000) == 0) {
                if (msg.type == MSG_SHUTDOWN) {
                    break;
                }
            }
            update_thread_heartbeat(*tid);
        }
        goto exit;
    }
    
    // 模拟音频设备初始化
    usleep(50000); // 50ms初始化时间
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 检查消息
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 0) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("Audio thread received shutdown message", 0);
                break;
            }
        }
        
        // 模拟音频采集 (48kHz, 16bit, 1024 samples per frame)
        // 1024 samples at 48kHz = ~21ms per frame
        
        sample_count += 1024;
        
        // 模拟音频处理
        usleep(5000); // 5ms处理时间
        
        // 创建音频数据消息
        message_t audio_msg = {
            .type = MSG_AUDIO_FRAME,
            .timestamp = get_system_timestamp(),
            .source_thread = *tid,
            .dest_thread = THREAD_STORAGE,
            .data_size = 1024 * 2 // 16bit samples
        };
        
        // 模拟音频数据
        memset(audio_msg.data, sample_count % 256, audio_msg.data_size);
        
        // 发送给存储线程
        if (message_queue_send(&g_camera_system.message_queues[THREAD_STORAGE], 
                              &audio_msg) != 0) {
            LOG_DEBUG("Failed to send audio frame to storage", 0);
        }
        
        // 音频采样率控制
        usleep(21000); // ~21ms for 48kHz/1024 samples
    }
    
exit:
    LOG_INFO("Audio capture thread exiting", 0);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}